from typing import List, Dict, Tuple, Any
import yaml
import os
from tools.log_util import INFO, ERROR, WARNING
from tools.vm_api_client import VMAPIClient

# 从YAML配置文件加载VM_IDS_RAW_DATA
with open(os.path.join(os.path.dirname(__file__), 'config_yaml', 'vm_ids.yaml'), 'r', encoding='utf-8') as f:
    vm_ids_config = yaml.safe_load(f)
VM_IDS_RAW_DATA = vm_ids_config['VM_IDS_RAW_DATA']


def parse_vmids(data_str: str) -> List[str]:
    """
    将原始字符串解析为 VMID 列表
    Args:
        data_str: 包含 VMID 的原始字符串，用逗号分隔
    Returns:
        VMID 列表
    """
    return [item.strip() for item in data_str.split(',') if item.strip()]


def extract_os_states(vms: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[int], List[Dict[str, Any]]]:
    """
    提取所有 VM 的 osState、osState=2 和 osState=5 的信息
    Args:
        vms: 虚拟机数据列表
    Returns:
        (所有 osState 信息, osState=2 的 VMID 列表, osState=5 的 VMID 和 projectName 字典列表)
    """
    os_states = []
    vmids_with_osstate_2 = []
    vmids_with_osstate_5 = []

    for vm in vms:
        os_state = vm.get('osState')
        vmid = vm.get('vmid')
        os_states.append({'vmid': vmid, 'osState': os_state})

        if os_state == 2:
            vmids_with_osstate_2.append(vmid)
        if os_state == 5:
            project_name = vm.get('projectName', '未知')
            vmids_with_osstate_5.append({'vmid': vmid, 'projectName': project_name})

    return os_states, vmids_with_osstate_2, vmids_with_osstate_5


def format_vmid_list(vmids: list, per_line: int = 10) -> str:
    """
    美化VMID列表输出，每行per_line个
    """
    lines = []
    for i in range(0, len(vmids), per_line):
        line = ', '.join(str(vmid) for vmid in vmids[i:i + per_line])
        lines.append(line)
    return '\n'.join(lines)


def format_vmid_project_list(vm_data: List[Dict[str, Any]], per_line: int = 5) -> str:
    """
    美化VMID和projectName列表输出，每行per_line个
    """
    lines = []
    for i in range(0, len(vm_data), per_line):
        line = ', '.join(f"{item['vmid']}: {item['projectName']}" for item in vm_data[i:i + per_line])
        lines.append(line)
    return '\n'.join(lines)


def print_summary(vmids: List[str], vmids_with_osstate_2: List[int], vmids_with_osstate_5: List[Dict[str, Any]]) -> None:
    """
    打印统计信息，包括osState=2和osState=5
    """
    INFO.logger.info(f"总的 VMID 数量: {len(vmids)}")
    INFO.logger.info(f"osState=2 的 VMID 数量: {len(vmids_with_osstate_2)}")
    INFO.logger.info(f"osState=2 的 VMID（共{len(vmids_with_osstate_2)}个）:\n{format_vmid_list(vmids_with_osstate_2)}")
    INFO.logger.info(f"osState=5（关机） 的 VMID 数量: {len(vmids_with_osstate_5)}个:\n{format_vmid_project_list(vmids_with_osstate_5)}")


def main(vm_ids_data: str = VM_IDS_RAW_DATA) -> Tuple[List[Dict[str, Any]], List[int], List[Dict[str, Any]]]:
    """
    主函数成功获取虚拟机数据
    Args:
        vm_ids_data: 包含 VMID 的原始字符串
    Returns:
        (所有 osState 信息, osState=2 的 VMID 列表, osState=5 的 VMID 和 projectName 字典列表)
    """
    try:
        vmids = parse_vmids(vm_ids_data)
        client = VMAPIClient()

        response = client.get_vm_data_by_ids(vmids)
        vms = response.get('body', {}).get('vms', [])

        if not vms:
            WARNING.logger.warning("未获取到任何虚拟机数据")
            return [], [], []

        os_states, vmids_with_osstate_2, vmids_with_osstate_5 = extract_os_states(vms)
        print_summary(vmids, vmids_with_osstate_2, vmids_with_osstate_5)

        return os_states, vmids_with_osstate_2, vmids_with_osstate_5
    except Exception as e:
        ERROR.logger.error(f"执行过程中发生错误: {e}")
        raise


if __name__ == '__main__':
    main()
